package com.googlecode.tracey.headers.jms;

import com.googlecode.tracey.id.TraceyId;
import com.googlecode.tracey.id.TraceyIdValue;

import javax.jms.JMSException;
import javax.jms.Message;

import static com.googlecode.tracey.headers.Headers.TRACEY_ID_HEADER_NAME;
import static com.googlecode.tracey.headers.Headers.MESSAGE_ID;
import static com.googlecode.tracey.id.TraceyIdValue.traceyIdValue;

public class TraceyJmsHeaders {

    public static TraceyIdValue setFrom(Message message) throws JMSException {
        final String stringValue = message.getStringProperty(TRACEY_ID_HEADER_NAME);
        if (exists(stringValue)) {
            return TraceyId.set(traceyIdValue(stringValue));
        } else {
            return null;
        }
    }

    private static boolean exists(String stringValue) {
        return stringValue != null && stringValue.trim().length() > 0;
    }

    public static <T extends Message> T setOn(T message) throws JMSException {
        if (TraceyId.hasValue()) {
            message.setStringProperty(TRACEY_ID_HEADER_NAME, TraceyId.get().value());
        }

        return message;
    }

    public static void usingTraceyIdIn(Message message, Runnable whatToDo) {
        try {
            setFrom(message);
            whatToDo.run();
        } catch (JMSException e) {
            throw new RuntimeException("Scoping tracey id from JMS message", e);
        } finally {
            TraceyId.clear();
        }
    }

}
